#include <widgets.hpp>
#include <QPainter>
#include <QHBoxLayout>
#include <QColorDialog>

using namespace TCWidgets;

TCColorButton::TCColorButton(QColor color, QWidget *parent) :
    QPushButton(parent)
{
    m_Color = QColor(color);
    setFixedSize(24, 24);
}

void
TCColorButton::paintEvent(QPaintEvent *event)
{
    QPushButton::paintEvent(event);
    QPainter painter(this);
    QRect    trect;

    trect = QRect(rect());

    trect.adjust(4, 4, -5, -6);
    painter.fillRect(trect, m_Color);
    painter.drawRect(trect);

    painter.end();
}

void
TCColorButton::setColor(QColor color)
{
    m_Color = QColor(color);
    repaint();
}

TCColorSelector::TCColorSelector(QString label, QColor color, QWidget *parent) :
    QWidget(parent)
{
    initialize(label, color);
}

TCColorSelector::TCColorSelector(QString label, QPen pen, QWidget *parent) :
    QWidget(parent)
{
    initialize(label, pen.color());
}

void
TCColorSelector::initialize(QString label, QColor color)
{
    QHBoxLayout *layout = NULL;

    layout     = new QHBoxLayout;
    m_Label    = new QLabel(label, this);
    m_Selector = new TCColorButton(color);
    m_Color    = QColor(color);

    layout->addWidget(m_Selector);
    layout->addWidget(m_Label);
    layout->addStretch();

    connect(m_Selector, SIGNAL(clicked()), this, SLOT(show_color_dialog()));

    setLayout(layout);
}

void
TCColorSelector::setColor(QColor color)
{
    m_Color = QColor(color);
    m_Selector->setColor(m_Color);

    emit colorSelected();
}

void
TCColorSelector::setColor(QPen pen)
{
    m_Color = pen.color();
    m_Selector->setColor(m_Color);
}

QColor
TCColorSelector::color()
{
    return m_Color;
}

void
TCColorSelector::show_color_dialog()
{
    QColorDialog dialog;

    dialog.setCurrentColor(m_Color);
    dialog.exec();
    m_Color = dialog.selectedColor();
    m_Selector->setColor(m_Color);

    emit colorSelected();
}

